import Layout from '@/layout/index'

// 递归判断列表，把最后的children设为undefined
export function getTreeData(data, childrenName) {
  for (let i = 0; i < data.length; i++) {
    if (data[i][childrenName].length == 0) {
      // children若为空数组，则将children设为undefined
      data[i][childrenName] = undefined
    } else {
      // children若不为空数组，则继续 递归调用 本方法
      getTreeData(data[i][childrenName], childrenName)
    }
  }
  return data
}

// 遍历后台传来的路由字符串，转换为组件对象
export function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (route.component) {
      if (route.parentId === '-1') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views${view}`)
  }
}
